from pymysqlpool import ConnectionPool

class SaveData(object):
    def __init__(self):
        self.config = {
            'pool_name': 'local',
            'host': 'localhost',
            'port': 3306,
            'user': 'root',
            'password': 'mq1989',
            'database': 'test',
            'max_pool_size': 50
        }

    def connection_pool(self):
        # Return a connection pool instance
        pool = ConnectionPool(**self.config)
        return pool

    def find_house(self, table, column, data):
        _sql = "select 1 from " + table + " where " + column + "=(%s) limit 1"
        with self.connection_pool().cursor() as cursor:
            result = cursor.execute(_sql, (data, ))
        return result

    def insert(self, table, _sql, item):
        if item.get("tpcflj"):
            result = self.find_house(table, 'tpcflj', item['tpcflj'])
        else:
            result = self.find_house(table, 'gpfyid', item['gpfyid'])

        if result != 1:
            with self.connection_pool().cursor() as cursor:
                cursor.execute(_sql, tuple(item.values()))

    # def update(self, table, _sql, item):
    #     with self.connection_pool().cursor() as cursor:
    #         cursor.execute(_sql, tuple(item.values()))

    def save(self, item):
        if len(item) == 3:
            table = 'pic_info'
        else:
            table = 'house_info'

        column_str = ''
        value_str = ''
        for key in item.keys():
            column_str = column_str + " " + key + ","
            value_str = value_str + " %s,"
        _sql = "INSERT INTO {}({}) VALUES({})".format(table, column_str[1:-1], value_str[1:-1])
        self.insert(table, _sql, item)


if __name__ == "__main__":
    # 测试
    pool = SaveData()
    result = pool.find_house('house_info', 'gpfyid', 2359669)
    print(result)
    item = {'cqmc': '杭州', 'cyrybh': 'HZ_990009578', 'fczsh': '杭房权证经移字第14894258号', 'fwtybh': '180607168981',
            'fwytValue': '住宅', 'gpfyid': 2412975, 'gplxrdh': '15068717477', 'gplxrxm': '钱梦潮', 'gpztValue': '挂牌成功',
            'hxs': 2, 'hxt': 2, 'hxw': 1, 'jzmj': 75.82, 'szlc': '22', 'szlcname': '中层', 'wtcsjg': 255, 'xqmc': '保利东湾',
            'xzqhname': '杭州市'}
    pool.save(item)
